package com.mvc.web.common.utils;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.log4j.Logger;


/** 
 * @ClassName: MailUtil 
 * @Description: 发送邮件工具类
 * @author: baihaian(baiha@jizhicar.com) 2017年6月20日 下午3:55:13
 */
public class MailUtil {
	private static final Properties config;
	private static Logger logger = Logger.getLogger(PropertiesUtil.class);
	
	/*
     * 发送消息体 回话 桥接
     */
	private MimeMessage message;
    private Session session;
    private Transport transport;
    /*
     * 接受者 主题 内容 接受邮箱 附件
     */
    private String subject;
    private String content;
    private String receiveMail;
    private File attachment;
    /*
     * 发送者 host 用户名  密码
     */
    private static String mailHost;
    private static String sender_username;
    private static String sender_password;
    
    
    
    /*
     * 初始化方法
     */
    static {
		config = new Properties();
		try {
			config.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("mailServer.properties"));
			mailHost = config.getProperty("mail.smtp.host");
            sender_username = config.getProperty("mail.sender.username");
            sender_password = config.getProperty("mail.sender.password");
		} catch (IOException e) {
			 e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}
    
    public MailUtil(String subject, String content, String receiveMail, File attachment) {
    	this.session = Session.getInstance(config);
    	this.message = new MimeMessage(session);
        this.subject=subject;
        this.content=content;
        this.receiveMail=receiveMail;
        this.attachment=attachment;
    }
    
    
    /**
     * 发送邮件
     * 
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     * @param receiveMail
     *            收件人地址
     * @param attachment
     *            附件
     */
    public void sendEmail() {
        try {
            // 发件人
        	long time1=System.currentTimeMillis();
            InternetAddress from = new InternetAddress(sender_username);
            message.setFrom(from);
 
            // 收件人
            InternetAddress to = new InternetAddress(receiveMail);
            message.setRecipient(Message.RecipientType.TO, to);
 
            // 邮件主题
            message.setSubject(subject);
            
            message.setSentDate(new Date());
 
            // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
            Multipart multipart = new MimeMultipart();
             
            // 添加邮件正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(content, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);
             
            // 添加附件的内容
            if (attachment != null) {
                BodyPart attachmentBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachment);
                attachmentBodyPart.setDataHandler(new DataHandler(source));
                 
                // 网上流传的解决文件名乱码的方法，其实用MimeUtility.encodeWord就可以很方便的搞定
                // 这里很重要，通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
                //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");
                 
                //MimeUtility.encodeWord可以避免文件名乱码
                attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
                multipart.addBodyPart(attachmentBodyPart);
            }
             
            // 将multipart对象放到message中
            message.setContent(multipart);
            // 保存邮件
            message.saveChanges();
            
            transport = session.getTransport("smtp");
            // smtp验证，就是你用来发邮件的邮箱用户名密码
            transport.connect(mailHost, sender_username, sender_password);
            // 发送
            transport.sendMessage(message, message.getAllRecipients());
            long time2 = System.currentTimeMillis();
            System.out.println("send success! 用时："+(time2-time1));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (transport != null) {
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    public static void main(String[] args) {
//    	File affix = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\a.zip");
    	MailUtil mu = new MailUtil("邮件主题", "邮件内容<br>http://loan-file.oss-cn-beijing.aliyuncs.com/14993251486031499325148604547100159.jpg", "baiha@jizhicar.com", null);
    	mu.sendEmail();
    }
}
